package com.example.tutorial.java.concurrent.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: cph
 * @date: 2022-4-9
 */
public class ThreadPoolTest {

    public static void main(String[] args) {
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        threadPoolTest.test();
    }

    private void test() {
        MyThreadFactory threadFactory = new MyThreadFactory("交易线程");
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 30,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(11),
                threadFactory,
                new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i <= 20; i++) {
            executor.execute(() -> System.out.println(Thread.currentThread().getName()));
        }
    }

    class MyThreadFactory implements ThreadFactory {

        private final String namePrefix;
        private final AtomicInteger nextId = new AtomicInteger(1);

        public MyThreadFactory(String group) {
            this.namePrefix = group + ",线程编号: ";
        }

        @Override
        public Thread newThread(Runnable r) {
            String name = namePrefix + nextId.getAndIncrement();
            return new Thread(null, r, name, 0);
        }
    }
}
